api = {}
window.APP.api = api

apiRoot = APP.config.apiRoot

AjaxOption = (type, data, settings) ->
    @type = type

    if type == "POST" || type == "PUT" || type == "DELETE"
        @data = data && JSON.stringify(data)
        @contentType = "application/json"
    else
        @data = data

    this.beforeSend = (request) ->
        request.setRequestHeader("X-username", APP.user?.username)
        request.setRequestHeader("X-token", APP.user?.token)

    @cache = false; # !!!

    _.extend(this, settings) if settings?

failHandler = (jqxhr) ->
    if jqxhr.status == 401
        APP.navigate "signIn"
    else if jqxhr.status == 403
        alert("您没有权限进行此项操作！")

api.get = (relativeUrl, data, settings) ->
    $.ajax(apiRoot + relativeUrl, new AjaxOption("GET", data, settings)).fail(failHandler)

api.getAbsolute = (absoluteUrl, data, settings) ->
    $.ajax(absoluteUrl, new AjaxOption("GET", data, settings)).fail(failHandler)

api.post = (relativeUrl, data, settings) ->
    $.ajax(apiRoot + relativeUrl, new AjaxOption("POST", data, settings)).fail(failHandler)

api.put = (relativeUrl, data) ->
    $.ajax(apiRoot + relativeUrl, new AjaxOption("PUT", data)).fail(failHandler)

api.remove = (relativeUrl, data) ->
    $.ajax(apiRoot + relativeUrl, new AjaxOption("DELETE", data)).fail(failHandler)

api.sendSecurityCode = (type, account)->
    api.post "securityCode/#{type}/#{account}"
